package com.zhoupeisen.command;

import com.netflix.hystrix.*;
import com.zhoupeisen.entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.web.client.RestTemplate;

/**
 * @ClassName OrderCommand
 * @Description TODO
 * @Author Administrator
 * @Data 下午 11:02
 * @Version 1.0
 **/
public class OrderCommand extends HystrixCommand<Product> {

    private RestTemplate restTemplate;

    private Long id;

    public OrderCommand(RestTemplate restTemplate , Long id){
        super(setter());
        this.restTemplate = restTemplate;
        this.id = id;
    }

    private static Setter setter() {
        //服务分组
        HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("order_product");
        //服务标识
        HystrixCommandKey commandKey = HystrixCommandKey.Factory.asKey("product");
        //线程池名称
        HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("order_product_pool");
        /*
         * 线程池配置
         * withCoreSize 核心线程大小50
         * withKeepAliveTimeMinutes 空闲线程存活时间15
         * withQueueSizeRejectionThreshold 缓存队列大小100，超过将执行拒绝策略
        **/
        HystrixThreadPoolProperties.Setter threadPoolProperties = HystrixThreadPoolProperties.Setter()
                .withCoreSize(50)
                .withKeepAliveTimeMinutes(15)
                .withQueueSizeRejectionThreshold(100);

        HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter()
                //采用线程池方式实现服务隔离
                .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD)
                .withExecutionTimeoutEnabled(false);


        return Setter.withGroupKey(groupKey).andCommandKey(commandKey).andThreadPoolKey(threadPoolKey).andThreadPoolPropertiesDefaults(threadPoolProperties).andCommandPropertiesDefaults(commandProperties);
    }

    @Override
    protected Product run() throws Exception {
        return restTemplate.getForObject("http://127.0.0.1/product/"+id,Product.class);
    }

    @Override
    /**
     *  降级方法
     *  当线程池缓存队列满，执行拒绝策略的时候，执行降级方法
    **/

    protected Product getFallback() {
        Product product = new Product();
        product.setProductName("不好意思，出错了");
        return null;
    }
}
